<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '退货申请'
  }
}
</route>
<template>
  <view class="return-page">
    <view class="content">
      <!-- 订单信息 -->
      <view class="order-info">
        <view class="order-row">
          <view>订单：{{ order.orderCode }}</view>
          <view>{{ order.detailNum }}种/{{ order.totalNum }}件</view>
        </view>
        <view class="order-row">
          <text class="refund-amount">
            最多可退
            <text class="amount">{{ oldTotalAmount }}元</text>
            元
          </text>
        </view>
      </view>

      <!-- 申请类型 -->
      <view class="form-item">
        <text class="label">申请类型</text>
        <picker @change="onReturnTypeChange" :value="asType" :range="returnTypeOptions">
          <view class="picker-value">
            {{ asType || order.type }}
          </view>
        </picker>
      </view>

      <!-- 订单状态 -->
      <view class="form-item">
        <text class="label">
          订单状态 :
          <text class="status">{{ order.orderStatus }}</text>
        </text>
      </view>

      <!-- 申请原因 -->
      <view class="form-item">
        <text class="label">申请原因</text>
        <picker @change="onReturnReasonChange" :value="applyReason" :range="returnReasonOptions">
          <view class="picker-value">
            {{ applyReason || '' }}
          </view>
        </picker>
      </view>

      <!-- 商品选择 -->
      <view class="products-section" v-if="returnType == '部分退'">
        <view class="section-header">
          <text>请选择需退货的商品（仅可选商家已经发出商品）及数量</text>
        </view>
        <wd-search v-model="searchValue" placeholder="请输入UPC/商品名称" cancel-txt="搜索" @cancel="searchCancel" />
        <view style="display: flex; align-items: center; padding: 0 16px">
          <text style="margin-right: 10px">全选</text>
          <!-- <checkbox :value="allcheck" :checked="allcheck" @click="AllCheckboxChange" /> -->

          <view :class="!!allcheck ? 'checkbox-fn' : 'checkbox-select'" @click="AllCheckboxChange">
            <wd-icon name="check-bold" size="22px" color="#fff" v-show="allcheck"></wd-icon>
          </view>
        </view>
        <view class="product-item" v-for="(item, index) in arrorder" :key="index">
          <view class="checkbox-wrapper">
            <view :class="!!item.selected ? 'checkbox-fn' : 'checkbox-select'" @click="onCheckboxChange($event, item)">
              <wd-icon name="check-bold" size="22px" color="#fff" v-show="allcheck"></wd-icon>
            </view>
          </view>
          <view class="product-image">
            <wd-img :src="item.mainPic" width="100%" height="100%"></wd-img>
          </view>
          <view class="product-details">
            <text class="product-title">{{ item.productName }}</text>
            <view class="price-row">
              <text class="price">¥{{ item.productPrice }}</text>
              <text class="unit">/箱</text>
            </view>
            <view class="quantity-row">
              <text class="spec">{{ item.package }}</text>
              <view class="number-input">
                <text class="minus" @click="updateQuantity(item, -1, index)">-</text>
                <input type="number" v-model="item.orderQuantity" class="quantity-input" @change="changeQuantity(item, index)" />
                <text class="plus" @click="updateQuantity(item, 1, index)">+</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 申请金额 -->
      <view class="form-item">
        <text class="label">
          <text style="color: red">*</text>
          申请金额
        </text>
        <view class="amount-input">
          <input type="number" v-model="order.totalAmount" placeholder="请输入申请金额" disabled />
          <text class="unit">元</text>
        </view>
      </view>

      <!-- 申请说明 -->
      <view class="form-item">
        <text class="label">
          <text style="color: red">*</text>
          申请说明
        </text>
        <textarea v-model="asNotes" placeholder="您还可以输入170字" :maxlength="170" class="reason-input" />
      </view>

      <!-- 图片上传 -->
      <view class="form-item">
        <text class="label">
          <text style="color: red">*</text>
          上传图片
        </text>
        <view class="upload-area-wrapper">
          <view class="upload-area" v-for="(item, index) in imgList" :key="index">
            <wd-img :src="item" width="100%" height="100%" @click="uploadShowFn(item, index)"></wd-img>
          </view>
          <view class="upload-area" @click="uploadImage">
            <text class="upload-text">+</text>
          </view>
        </view>
      </view>
    </view>
    <wd-action-sheet v-model="uploadShow" :actions="showActions" @close="uploadClose" @select="uploadSelect" />
    <view class="submit-wrapper">
      <htm-button type="primary" custom-style="width: 90vw" @click="submitReturn"> 提交申请 </htm-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ASuploadFile, AddAs } from '@/service/after-sale/after-sale'
import { getEnvBaseUrl } from '@/utils/index'
const returnTypeOptions = ['仅退款-整单退', '仅退款-部分退', '退货退款-整单退', '退货退款-部分退']
const returnReasonOptions = ['缺货', '少发漏发', '破损/产品有污染', '赠品', '其他']

const asType = ref('仅退款-整单退')
const applyReason = ref('缺货')
const asNotes = ref('')

const returnType = ref('')

const onReturnTypeChange = (e: any) => {
  asType.value = returnTypeOptions[e.detail.value]
  if (asType.value == '仅退款-整单退' || asType.value == '退货退款-整单退') {
    returnType.value = '整单退'
  } else {
    returnType.value = '部分退'

    order.value.details.forEach((item) => {
      item.orderQuantity = 0
    })
    order.value.totalAmount = 0
    searchCancel()
  }
}

const onReturnReasonChange = (e: any) => {
  console.log(e)
  applyReason.value = returnReasonOptions[e.detail.value]
}
const allcheck = ref(false)
const AllCheckboxChange = () => {
  allcheck.value = !allcheck.value
  console.log('AllChangeboxChange 被触发', order.value.details)
  let isTrue = false
  order.value.details.forEach((item) => {
    if (item.selected == false) {
      console.log(`item.selected->`, item.selected)
      // 当有一个为false时，说明不是全选
      isTrue = true
    }
  })
  if (isTrue) {
    console.log('不是全选')
    order.value.details.forEach((item) => {
      item.selected = true
    })
  } else {
    console.log('是全选')
    order.value.details.forEach((item) => {
      item.selected = false
    })
  }

  // 计算总金额
  initTotalMethod()
}

const initTotalMethod = () => {
  const selectedProducts = []
  console.log(order.value.details)
  order.value.details.forEach((item) => {
    if (item.selected) {
      selectedProducts.push(item)
    }
  })
  const arr = selectedProducts.map((item) => {
    return {
      asQuantity: item.orderQuantity,
      productPrice: item.productPrice,
      upcCode: item.upcCode
    }
  })

  setTimeout(() => {
    let total = 0
    arr.forEach((item) => {
      console.log(item)
      total = total + Number(Number(item.productPrice * item.asQuantity).toFixed(2))
    })
    console.log(total)
    order.value.totalAmount = total
  })
}

const onCheckboxChange = (e: any, item: any) => {
  console.log('onCheckboxChange 被触发')
  console.log('全选', allcheck)
  allcheck.value = false
  item.selected = !item.selected
  console.log('商品选中状态：', item.selected)

  // 计算总金额
  initTotalMethod()
}

const updateQuantity = (item: any, delta: number, index: number) => {
  const newValue = Number(item.orderQuantity) + delta
  if (newValue >= 0 && newValue <= initArr.value[index].asQuantity) {
    item.orderQuantity = newValue
    initTotalMethod()
  } else {
    uni.showToast({
      title: '数量超出限制',
      icon: 'none'
    })
  }
}
const imgList = ref([])
const uploadImage = () => {
  const baseUrl = getEnvBaseUrl()
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      try {
        const tempFilePath = res.tempFilePaths[0]
        // 使用uni.uploadFile上传文件
        uni.uploadFile({
          url: baseUrl + '/jeecg-boot/sys/common/upload',
          filePath: tempFilePath,
          name: 'file',
          formData: {
            biz: 'XMHM00104'
          },
          success: (uploadRes) => {
            const result = JSON.parse(uploadRes.data)
            if (result) {
              uni.showToast({
                title: '上传成功',
                icon: 'success'
              })
            }
            imgList.value.push(result.message)
            console.log(imgList.value)
          },
          fail: (error) => {
            console.error('上传错误：', error)
            uni.showToast({
              title: '上传失败',
              icon: 'error'
            })
          }
        })
      } catch (error) {
        console.error('上传错误：', error)
        uni.showToast({
          title: '上传失败',
          icon: 'error'
        })
      }
    }
  })
}
const imgUrl = ref('')
const imgIndex = ref(0)
const uploadShowFn = (url: string, index: number) => {
  uploadShow.value = true
  imgUrl.value = url
  imgIndex.value = index
}

const uploadShow = ref<boolean>(false)
const showActions = ref([
  {
    name: '预览'
  },
  {
    name: '删除'
  }
])

function uploadClose() {
  uploadShow.value = false
}
const changeQuantity = (item: any, index: number) => {
  console.log(item.orderQuantity, index)
  if (item.orderQuantity <= 0) {
    item.orderQuantity = 1
    uni.showToast({
      title: '数量不能小于1',
      icon: 'none'
    })
  }
  // 计算总金额
  initTotalMethod()
}

function uploadSelect({ item, index }) {
  console.log(`当前选中项: ${item.name}, 下标: ${index}`)
  if (item.name === '预览') {
    uni.previewImage({
      urls: [imgUrl.value],
      current: imgUrl.value
    })
  }
  if (item.name === '删除') {
    imgList.value.splice(imgIndex.value, 1)
  }
}
const searchValue = ref('')
const arrorder = ref([])
const searchCancel = () => {
  console.log(searchValue.value)
  if (searchValue.value == '') {
    arrorder.value = order.value.details
  } else {
    arrorder.value = order.value.details.filter((item) => {
      return item.productName.includes(searchValue.value) || item.upcCode.includes(searchValue.value)
    })
  }
}

// 处理数据
const handleData = () => {
  const selectedProducts = []
  console.log(order.value.details)
  order.value.details.forEach((item) => {
    if (!item.selected) {
      selectedProducts.push(item)
    }
  })
  const arr = selectedProducts.map((item) => {
    return {
      asQuantity: item.orderQuantity,
      productPrice: item.productPrice,
      upcCode: item.upcCode
    }
  })
  console.log(arr)
  return arr
}

const checkData = () => {
  if (!!order.value.totalAmount && !!asNotes.value && imgList.value.length > 0) {
    return true
  }
  return false
}

const submitReturn = () => {
  const isOk = checkData()
  if (!isOk) {
    uni.showToast({
      title: '请填写完整',
      icon: 'none'
    })
    return
  }
  const selectedProducts = []

  order.value.details.forEach((item) => {
    if (item.selected) {
      selectedProducts.push(item)
    }
  })
  const details = selectedProducts.map((item) => {
    return {
      asQuantity: item.orderQuantity,
      productPrice: item.productPrice,
      upcCode: item.upcCode
    }
  })

  const param = {
    applyAttachments: imgList.value.join(','),
    applyReason: applyReason.value,
    asType: asType.value,
    asNotes: asNotes.value,
    details: returnType.value == '整单退' ? [] : details,
    orderCode: order.value.orderCode,
    storeCode: order.value.storeCode,
    storeName: order.value.storeName,
    totalAmount: order.value.totalAmount
  }
  AddAs(param).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateBack({
          delta: 3
        })
      }, 1000)
    } else {
      uni.showToast({
        title: res.message,
        icon: 'none'
      })
    }
  })
  console.log(param)
}
const order = ref({})

const detail = ref('')
const asCode = ref('')

const initArr = ref([])
const oldTotalAmount = ref(0)
onLoad((options) => {
  order.value = JSON.parse(options.order)
  oldTotalAmount.value = JSON.parse(order.value.totalAmount)
  // asType.value = order.value.type
  order.value.details.forEach((item) => {
    item.selected = false
  })

  initArr.value = handleData()
  console.log('initArr.value')
  console.log(initArr.value)
})
</script>

<style lang="scss" scoped>
:deep(.data-v-82a7a455 .wd-popup--bottom) {
  bottom: 80rpx;
}
:deep(.data-v-4ebafd4c .wd-search) {
  width: 80vw;
}

.checkbox-fn {
  width: 15px;
  height: 15px;
  border: 1px solid #ccc;
  border-radius: 50%;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
  padding: 4px;
}

.checkbox-select {
  width: 15px;
  height: 15px;
  border: 1px solid #ccc;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
  padding: 4px;
}

.checkbox-wrapper .checkbox {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #f56c6c;
}

.checkbox-wrapper .checkbox.unchecked {
  background-color: #ccc;
}

.return-goods-order {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.return-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
  position: relative;
}

.content {
  padding: 16px;
}

.order-info {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;

  .order-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .refund-amount {
    font-size: 14px;
    color: #666;

    .amount {
      color: #f56c6c;
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.form-item {
  background: #fff;
  padding: 10px 16px;
  .label {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    display: block;
  }

  .status {
    color: #666;
    font-size: 14px;
  }
}

.products-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;

  .section-header {
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 14px;
    color: #666;
  }

  .product-item {
    display: flex;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .checkbox-wrapper {
      display: flex;
      align-items: center;
      margin-right: 12px;
    }

    .product-image {
      width: 80px;
      height: 80px;
      border-radius: 4px;
      margin-right: 12px;
    }

    .product-details {
      flex: 1;

      .product-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }

      .price-row {
        margin-bottom: 8px;

        .price {
          color: #f56c6c;
          font-size: 15px;
          font-weight: 500;
        }

        .unit {
          color: #999;
          font-size: 12px;
          margin-left: 4px;
        }
      }

      .quantity-row {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .spec {
          color: #999;
          font-size: 12px;
        }
      }
    }
  }
}

.amount-input {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 8px;

  input {
    flex: 1;
    border: none;
    outline: none;
    font-size: 14px;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }

  .unit {
    color: #666;
    font-size: 14px;
    margin-left: 4px;
  }
}

.modify-amount {
  color: #f56c6c;
  font-size: 14px;
}
.upload-area-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.upload-area {
  width: 100px;
  height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  .upload-text {
    color: #999;
    font-size: 33px;
  }
}

.submit-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.picker-value {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
}

.number-input {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;

  .minus,
  .plus {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    color: #333;
    font-size: 18px;

    &:active {
      opacity: 0.8;
    }
  }

  .quantity-input {
    width: 40px;
    height: 28px;
    text-align: center;
    border: none;
    border-left: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    font-size: 14px;
  }
}

.reason-input {
  width: 100%;
  height: 100px;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.4;
}

button[type='primary'] {
  background-color: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;

  &:active {
    opacity: 0.9;
  }
}
</style>
